<template>
  <main-card-admin title="公开数据" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button
        style="margin-right: 8px; width: 36px; height: 36px"
        class="icon-only-btn"
        @click="fileTaskStore.changeTaskListOptions({ open: true })"
      >
        <i class="iconfont icon-tasklist-line"></i>
      </a-button>
      <a-button v-if="checkKey('admin-data-manage-add')" type="primary" @click="handleAdd">新建</a-button>
    </template>
    <template #screen-space>
      <div class="header-box">
        <div class="header-select">
          <a-select
            ref="select"
            v-model:value="selectClassify"
            class="w-140"
            :options="classifyOptions"
            :field-names="{ label: 'label', value: 'value' }"
            @change="selectChange"
          />
        </div>
        <div class="header-search">
          <a-input v-model:value="courseName" v-trim allow-clear placeholder="请输入名称" @press-enter="getNameChange">
            <template #prefix><SearchOutlined /></template>
          </a-input>
        </div>
      </div>
    </template>
    <div>
      <a-table
        :style="{ width: '100%' }"
        :data-source="dataList"
        :columns="taskTableColumns"
        :pagination="false"
        :custom-row="r => ({ onClick: () => handleToDetail(r) })"
        :loading="loading"
        class="header-right-angle admin-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'size'">
            {{ sizeFilter(record?.size || 0) }}
          </template>
          <template v-else-if="column.dataIndex === 'tools'">
            <a-dropdown
              v-if="checkKey('admin-data-manage-edit') || checkKey('admin-data-manage-del') || checkKey('admin-data-manage-download')"
              placement="bottomRight"
              @click.stop
            >
              <a-button type="text" class="icon-only-btn" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-if="checkKey('admin-data-manage-download')"
                    class="menu-icon-item"
                    @click.stop="handleDownLoad(record as PublicResponseListType)"
                  >
                    下载
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkKey('admin-data-manage-edit')"
                    class="menu-icon-item"
                    @click.stop="handleOpenDataSetForm(record as PublicResponseListType)"
                  >
                    编辑
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkKey('admin-data-manage-del')"
                    class="menu-icon-item"
                    @click.stop="handleDeleteDateSet(record as PublicResponseListType)"
                  >
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
          <template v-else>
            {{ replaceEmptyStr(record[column.dataIndex as string]) }}
          </template>
        </template>
      </a-table>
      <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
    </div>
  </main-card-admin>
  <edit-vue
    ref="dataSetFormRef"
    :loading="addLoading || editLoading"
    :title="editTitle"
    :ok-text="editOkText"
    @on-ok="handleDataSetSubmit"
  />
  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :msg="`已有${collectNumber}人收藏此数据集，请确认是否删除？`"
    label="请输入数据集名称"
    :confirm-name="deleteConfigName"
    :loading="confirmLoading"
    @ok="onOkDeleteTask"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { debounce, sizeFilter } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import manualMessage from '@/components/ManualMessage/index'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { adminCollectionApi, dataManageApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import { useFileTaskStore } from '../components/FileTaskCard/upload-store'
  import { ListRequest, PublicResponseListType } from '../types/index'
  import EditVue, { DataSetFormState, FormType } from './components/Edit.vue'

  interface SelectType {
    label: string
    value: string
    order: string
    columns: string
  }
  let router = useRouter()
  const selectClassify = ref<string>('创建时间降序')
  const classifyOptions = ref<SelectType[]>([
    {
      label: '创建时间降序',
      value: '创建时间降序',
      columns: 'createTime',
      order: 'desc'
    },
    {
      label: '创建时间升序',
      value: '创建时间升序',
      columns: 'createTime',
      order: 'asc'
    },
    {
      label: '数据集大小降序',
      value: '数据集大小降序',
      columns: 'size',
      order: 'desc'
    },
    {
      label: '数据集大小升序',
      value: '数据集大小升序',
      columns: 'size',
      order: 'asc'
    },
    {
      label: '文件数量降序',
      value: '文件数量降序',
      columns: 'fileNum',
      order: 'desc'
    },
    {
      label: '文件数量升序',
      value: '文件数量升序',
      columns: 'fileNum',
      order: 'asc'
    }
  ])
  //  收藏数量查询
  const collectNumber = ref(0)

  const fileTaskStore = useFileTaskStore()

  const selectChange = (value: string | any) => {
    classifyOptions.value.forEach((item: SelectType) => {
      if (item.label === value) {
        pageForm.value.columns = item.columns
        pageForm.value.order = item.order
        pageForm.value.name = courseName.value
        dataList.value = []
        pageForm.value.offset = 1
        getDataList()
      }
    })
  }

  const courseName = ref<string>('')
  const handleAdd = () => {
    editTitle.value = '创建数据集'
    editOkText.value = '创建'
    dataSetFormRef.value?.open('add', {})
  }

  // 表格列
  const taskTableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: 200
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description'
      },
      {
        title: '文件大小',
        dataIndex: 'size',
        key: 'size',
        width: 200
      },
      {
        title: '文件数',
        dataIndex: 'fileNum',
        key: 'fileNum',
        width: 200
      },
      {
        title: '',
        width: 60,
        dataIndex: 'tools'
      }
    ])
  )

  const { pageForm, loading, dataList, getDataList } = useList<ListRequest, PublicResponseListType>(dataManageApi.list, {
    columns: '',
    limit: 10,
    name: '',
    offset: 1,
    order: ''
  })
  getDataList()

  // 点击当前卡片进行跳转
  const handleToDetail = (data: PublicResponseListType) => {
    router.push({
      path: '/admin/data-manage/details-list',
      query: {
        id: data.id,
        name: data.name,
        pid: 0,
        groupName: '数据管理'
      }
    })
  }

  const handleDownLoad = async (item: PublicResponseListType) => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)
    try {
      const { data } = await dataManageApi.download(
        { id: item.id },
        {
          isResponseAll: true,
          timeout: 300000 //设置超时时长5min
        }
      )

      if (data.code === 'SYSTEM-100000') {
        manualMessage.destroy()
        await message.success({ content: '成功添加至任务队列', icon: '', key: 'downloading', duration: 2 })
        fileTaskStore.changeTaskListOptions({
          open: true,
          key: '2',
          showDownFailed: false
        })
      } else {
        console.log('下载失败')
        manualMessage.destroy()
        message.error({ content: data.message, key: 'downloading', duration: 2 })
      }
    } catch (error) {
      console.log('下载失败', error)
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }

  /**********************数据集删除卡片**********************************/
  const isDeleteDialogShow = ref<boolean>(false)
  const deleteConfigName = ref<string>('')
  const FAVORITE_TYPE_CASE = 3 //3表示收藏类型为数据集
  const handleDeleteDateSet = async (data: PublicResponseListType) => {
    // 获取数据集收藏列表
    deleteConfigName.value = data.name
    isDeleteDialogShow.value = true
    deleteID.value = data.id
    let { data: num } = await adminCollectionApi.numberOfCollections({ favoriteType: FAVORITE_TYPE_CASE, objectId: data.id })
    collectNumber.value = num
  }
  // 点击删除时获得的id
  const deleteID = ref<string>('')
  const { loading: confirmLoading, runAsync: runDelDataManage } = useRequest(dataManageApi.del)
  const onOkDeleteTask = async () => {
    await runDelDataManage({ id: deleteID.value }, { isAddUid: true })
    message.success('删除成功')
    isDeleteDialogShow.value = false
    dataList.value = []
    pageForm.value.offset = 1
    getDataList()
  }

  const handleOpenDataSetForm = (data: PublicResponseListType) => {
    editTitle.value = '编辑数据集'
    editOkText.value = '确认'
    console.log(data, 'data')
    dataSetFormRef.value?.open('edit', { ...data, describe: data.description })
  }

  /***********************创建数据集卡片**************/
  const dataSetFormRef = ref<InstanceType<typeof EditVue>>()
  const editTitle = ref<string>('创建数据集')
  const editOkText = ref<string>('创建')

  const { loading: addLoading, runAsync: runAddDataManage } = useRequest(dataManageApi.add)
  const { loading: editLoading, runAsync: runEditDataManage } = useRequest(dataManageApi.edit)
  const handleDataSetSubmit = async (_type: FormType, data: DataSetFormState) => {
    if (_type === 'add') {
      await runAddDataManage({ name: data.name, description: data.describe }, { isAddUid: true })
    } else {
      await runEditDataManage({ name: data.name, description: data.describe, id: data.id }, { isAddUid: true })
    }
    message.success(_type === 'add' ? '新增成功' : '编辑成功')
    pageForm.value.offset = 1
    dataList.value = []
    getDataList()
    dataSetFormRef.value?.close()
  }

  const getNameChange = debounce(() => {
    dataList.value = []
    pageForm.value.name = courseName.value
    pageForm.value.offset = 1
    getDataList()
  }, 500)
</script>
<style lang="less" scoped>
  .box {
    color: red;
  }

  .card-wrap {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(268px, 1fr));
    grid-gap: 24px 20px;
  }

  .header-box {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-select {
      width: 134px;
    }

    .header-search {
      width: 328px;
    }
  }
</style>
